<template>
	<div class="coursewareLiveWrap w944">
		<alert ref="alert"></alert>
		<div class="label_top">
			<p>{{courseName}}</p>
			<em @click="reBack">返回</em>
		</div>
		<div class="container">
			<el-tabs type="border-card">
		  		<el-tab-pane label="直播动态">
		  			<div class="liveDynamic">
						<div class="courseLiveState">
							<p><span>直播时间：</span>{{liveTime}}</p>
							<p><span>直播状态：</span>{{liveState}}</p>
						</div>
						<p class="huifangDiv" v-show="playWrap">回放操作：
							<el-button @click="handleDownload" class="green">下载</el-button>
							<el-button @click="handlePlayback" class="blue">编辑回放</el-button>
						</p>
					</div>
		  		</el-tab-pane>
		  		<el-tab-pane label="直播链接">
		  			<div class="liveSeen_inner">
					<el-tabs v-model="activeName">
					    <el-tab-pane label="讲师" name="first">
					    	<div class="fenleiDiv">
					    		<div class="line">
					    			<span>网页开播链接:</span>
					    			<input type="text" v-model="tip_1_url1"/>
					    		</div>
					    		<div class="line">
					    			<span>启动客户端链接:</span>
					    			<input type="text" v-model="tip_1_url2"/>
					    		</div>
					    		<p>频道号:{{tip_1_ChannelNo}}<i></i>密码/邀请码:{{tip_1_InviteCode}}</p>
					    	</div>
					    </el-tab-pane>
					    <el-tab-pane label="助教" name="second">
					    	<div class="fenleiDiv">
					    		<div class="line">
					    			<span>助教后台链接:</span>
					    			<input type="text" v-model="tip_2_url1"/>
					    		</div>
					    		<p class="clearFix">频道号:{{tip_2_ChannelNo}}<i></i>密码:{{tip_2_InviteCode}}</p>
					    	</div>
					    </el-tab-pane>
					    <el-tab-pane label="观众" name="third">
					    	<div class="fenleiDiv">
						    	<div class="line">
					    			<span>观众观看链接:</span>
					    			<input type="text" v-model="tip_3_url1"/>
					    		</div>
				    		</div>
					    </el-tab-pane>
					</el-tabs>
				</div>
		  		</el-tab-pane>
		  		<el-tab-pane label="报名管理">
		  			<div class="el-tabs-report">
						<div class="tongji">
							<span><b>{{baomingrenshu}}</b>报名人数</span>
							<span><b>{{yitongguo}}</b>已通过</span>
							<span><b>{{daishenhe}}</b>待审核</span>
						</div>
						<el-select v-model="auditStatus" placeholder="审核状态" class="th_2" @change="getCommentsList">
							<el-option label="审核状态" value=""></el-option>
							<el-option label="待审核" value="1"></el-option>
							<el-option label="已审核" value="2"></el-option>
							<el-option label="已拒绝" value="0"></el-option>
						</el-select>
						<div class="msearch">
							<input placeholder="请输入学员名字……" v-model="search"/>
							<a @click="getCommentsList"><img src="../../assets/qudaoImg/search.png"/></a>
						</div>
					</div>
					<el-table ref="multipleTable" :data="tableData" border @selection-change="handleSelectionChange">
						<el-table-column label="序号" width="60">
							<template slot-scope="scope">{{ scope.row.sort}}</template>
						</el-table-column>
						<el-table-column prop="nickname" label="学员名字"></el-table-column>
						<el-table-column prop="status" label="审核状态">
							<template slot-scope="scope">
								<span v-if="scope.row.status==1">待审核</span>
								<span v-if="scope.row.status==2">已通过</span>
								<span v-if="scope.row.status==0">已拒绝</span>
							</template>
						</el-table-column>
						<el-table-column prop="createTime" label="报名时间"></el-table-column>
						<el-table-column label="操作"> 
							<template slot-scope="scope">
								<div v-if="scope.row.status==1">
									<el-button @click="handlePass(scope.row)">通过</el-button>
									<el-button @click="handleRefuse(scope.row)" class="red">拒绝</el-button>
								</div>
								<el-button @click="handleRefuse(scope.row)" v-if="scope.row.status==2" class="red">拒绝</el-button>
								<el-button @click="handlePass(scope.row)" v-if="scope.row.status==0">通过</el-button>
							</template>
						</el-table-column>
					</el-table>
					<div class="fenyeMargin">
						<div class="pag_block">
							<el-pagination  @current-change="handleCurrentChange" :current-page="currentpage" :page-size="pagesize" layout="prev, pager, next" :total="total"></el-pagination>
						</div>
					</div>
		  		</el-tab-pane>
			</el-tabs>
		</div>
		<!--编辑回放-->
		<div class="editPlayBack" v-show="playBackWrap">
			<p><span>直播名称：</span>{{editPlayBackTitle}}</p>
			<div class="editPlayBackLine">
				<span>修改直播名称：</span>
				<input type="text" placeholder="修改直播名称" v-model="liveBroadcastName"/>
			</div>
			<div class="editPlayBackLine">
				<span>上传回放视频：</span>
				<a class="uploadVideoBtn"><input type="file" id="fileUpload" @change="fileChange($event)">选择文件</a>
				<button @click="authUpload" :disabled="uploadDisabled">开始上传</button>
				<span class="progress">上传进度: <i id="auth-progress">{{authProgress}}</i>%</span>
			</div>
			<div class="footerButton">
				<a @click="editPlayBackCheckSave">保存</a>
				<a @click="editPlayBackCancel" class="cancel">取消</a>
			</div>
		</div>
	</div>
</template>

<script>
	import axios from 'axios';
	import alert from '../../components/Alert.vue';
	export default{
		data(){
			return{
				liveBroadcastid:'',
				courseName:'',
				updateTitle:'',
				teacherTitle:'',
				lecturerid:'',
				
				//查看直播链接
				liveSeen:false,
				playWrap:false,
				activeName: 'first',//查看直播链接  默认位置
				liveTime:'',
				liveState:'',
				tip_1_url1:'',
				tip_1_url2:'',
				tip_1_ChannelNo:'',
				tip_1_InviteCode:'',
				
				tip_2_url1:'',
				tip_2_ChannelNo:'',
				tip_2_InviteCode:'',
				tip_3_url1:'', 
				tip_3_Img:'',
				//编辑回放
				editPlayBackTitle:'',
				liveBroadcastName:'',
				playBackWrap:false,
				aliyunVideoId:'',
				huifangId:'',
				huifangChannelId:'',
				
				auditStatus:'',
				auditStatusOption:[{
					id:1,
					name:'待审核'
				},{
					id:2,
					name:'已审核'
				},{
					id:0,
					name:'已拒绝'
				}],
				baomingrenshu:'',
				yitongguo:'',
				daishenhe:'',
				search:'',
				sort:'',
				pagesize: 15,
		        currentpage: 1,
		        total: 1,
		        tableData: [],
				multipleSelection: [],
				
				timeout: '60000',
				partSize: '1048576',
				parallel: '5',
				retryCount: '3',
				retryDuration: '2',
				region: 'cn-shanghai',
				userId: '1585664211304336', //1303984639806000
				file: null,
				authProgress: 0,
				uploadDisabled: true,
				resumeDisabled: true,
				pauseDisabled: true,
				uploader: null,
				statusText: '',
			}
		},
		methods:{
			getParams() {
				this.liveId = this.$route.params.liveId;
				this.liveBroadcastid = this.$route.params.liveBroadcastid;
				this.courseName = this.$route.params.courseName;
				this.updateTitle = this.$route.params.updateTitle;
				this.pathKey = this.$route.params.pathKey;
				this.teacherTitle = this.$route.params.teacherTitle;
				this.lecturerid = this.$route.params.lecturerid;
				console.log('courseWareLiveWrap:',this.$route.params);
			},
			getLiveDetails(){
				this.$ajax({
                    url: this.$root.jifuUrl + '/getLiveBroadcastChannelInfo?'+'liveBroadcastid='+this.liveBroadcastid,
                    method: 'GET',
                    data:{},
                    success: res => {
                        if(res.data.code == 200) {
							let resObj = res.data.data;
							this.liveTime = resObj.starttime;
							this.tip_1_url1 = resObj.webBroadcast;
							this.tip_1_url2 = resObj.clientBroadcast;
							this.tip_1_ChannelNo = resObj.channelId;
							this.tip_1_InviteCode = resObj.lecturerChannelPass;
							
							this.tip_2_url1 = resObj.assistantBroadcast;
							this.tip_2_ChannelNo = '001' + resObj.channelId;
							this.tip_2_InviteCode = resObj.assistantChannelPass;
							
							this.tip_3_url1 = resObj.userBroadcast;
							if(resObj.liveBroadcastStatus==0){
								this.liveState = '暂无直播'
							}else if(resObj.liveBroadcastStatus==1){
								this.liveState = '等待直播'
							}else if(resObj.liveBroadcastStatus==2){
								this.liveState = '正在直播'
							}else if(resObj.liveBroadcastStatus==3){
								this.liveState = '直播结束'
							}else if(resObj.liveBroadcastStatus==4){
								this.liveState = '直播回放';
								this.playWrap = true;
								this.huifangId = this.liveBroadcastid;
								this.huifangChannelId = resObj.channelId;
								this.videoUrl = resObj.videoUrl;
							}
                        }else{
							this.liveSeen = false;
							this.failText = res.data.message;
							this.$rootFunction().deleteResFail();
						}
                    }
                });
			},
			liveClose(){
				this.liveSeen = false;
			},
			handleDownload(){
				let s = {
					fileUrl:this.videoUrl,
					fileName:this.courseName
				};
				if (window.navigator.msSaveBlob) {
		          	try {
		            	window.navigator.msSaveBlob(blob, s.fileName)
		          	}catch (e) {
		            	console.log(e);
		          	}
		        }else {
					var downloadElement = document.createElement('a');
		          	downloadElement.href = s.fileUrl;
		          	downloadElement.target = '_blank';
		          	downloadElement.download = s.fileName; //下载后文件名
		          	document.body.appendChild(downloadElement);
		          	downloadElement.click(); //点击下载
		          	document.body.removeChild(downloadElement); //下载完成移除元素
		          	window.URL.revokeObjectURL(s.fileUrl); //释放掉blob对象
	            };
				var url = s.fileUrl;
			    var xhr = new XMLHttpRequest();
			    xhr.open('get', url,true); 
			    xhr.responseType = "blob"; // 返回类型blob
			    xhr.onload = function() {
			        // 请求完成
			        if(this.status == 200) {
				        var blob = this.response;
				        var href = window.URL.createObjectURL(blob);
	            	}
	        	}
	    		// 发送ajax请求
	    		xhr.send()
			},
			handlePlayback(){
				this.liveSeen = false;
				this.playBackWrap = true;
				this.editPlayBackTitle = this.courseName;
			},
			editPlayBackCheckSave(){
				let that = this;
				let s = {
					liveBroadcastid:this.huifangId,
					aliyunVideoId:this.aliyunVideoId,
					liveBroadcastName:this.liveBroadcastName,
					channelId:this.huifangChannelId
				};
				this.$ajax({
                    url: this.$root.jifuUrl + '/updateVideoIdByLiveBroadcastid',
                    method: 'POST',
                    data: this.qs.stringify(s),
                    success: res => { 
                        if(res.data.code == 200) {
							this.playBackWrap = false;
							this.$refs.alert.show({alertText: '保存成功'});
							setTimeout(() =>{
								this.$router.go(0);
							},2000) 
                        }else{
							this.playBackWrap = false;
							this.failText = res.data.message;
							this.$rootFunction().deleteResFail();
						}
                    }
                });
			},
			editPlayBackCancel(){
				this.playBackWrap = false;
			},
			getCommentsList(){
				let that = this;
				this.$ajax({
					url: this.$root.jifuUrl + "/getCourseLiveBroadcastSignupPage?"+'page='+this.currentpage+'&num='+this.pagesize+'&zbid='+this.liveBroadcastid+'&status='+this.auditStatus+'&name='+this.search,
					method: 'GET',
					data: {},
					success: res => {
						if(res.data.code == 200) {
							this.tableData = res.data.data.list;
							this.total=res.data.data.pageParam.items;
							for(var i = 0;i<this.tableData.length;i++){
								this.tableData[i].sort=i+1
							}
						}
					}
				});
			},
			getData(){
				let that = this;
				this.$ajax({
					url: this.$root.jifuUrl + "/getCourseLiveBroadcastSignupInfo?"+'zbid='+this.courseid,
					method: 'GET',
					data: {},
					success: res => {
						if(res.data.code == 200) {
							that.baomingrenshu = res.data.data.totalCnt;
							that.yitongguo = res.data.data.passCnt;
							that.daishenhe = res.data.data.shzCnt;
						}
					}
				});
			},
			handlePass(row){
				let that = this;
				let s = {
					id:row.id,
					status:2
				};
				this.$ajax({
					url: this.$root.jifuUrl + "/updateCourseLiveBroadcastSignupStatus",
					method: 'POST',
					data: this.qs.stringify(s),
					success: res => {
						if(res.data.code == 200) {
							this.$refs.alert.show({alertText: '保存成功'});
							setTimeout(() =>{
								this.$router.go(0);
							},2000) 
						}else{
							this.failText = res.data.message;
							this.$rootFunction().deleteResFail();
						}
					}
				});
			},
			handleRefuse(row){
				let that = this;
				let s = {
					id:row.id,
					status:0
				};
				this.$ajax({
					url: this.$root.jifuUrl + "/updateCourseLiveBroadcastSignupStatus",
					method: 'POST',
					data: this.qs.stringify(s),
					success: res => {
						if(res.data.code == 200) {
							this.$refs.alert.show({alertText: '保存成功'});
							setTimeout(() =>{
								this.$router.go(0);
							},2000) 
						}else{
							this.failText = res.data.message;
							this.$rootFunction().deleteResFail();
						}
					}
				});
			},
			toggleSelection(rows) {
				if(rows) {
					rows.forEach(row => {
						this.$refs.multipleTable.toggleRowSelection(row, !this.allSelect)
					})
					this.allSelect = !this.allSelect;
				}
			},
			handleSelectionChange(val) {
				this.multipleSelection = [];
				val.forEach(row => {
					this.multipleSelection.push(row.id);
				});
			},
			handleCurrentChange(value) {
				this.currentpage = value;
				this.getCommentsList();
			},
			reBack(){
				this.$router.push({
					name: 'courseware',
					params: {
						liveId:this.liveId,
						updateTitle:this.updateTitle,
						pathKey:this.pathKey,
						teacherTitle:this.teacherTitle,
						lecturerid:this.lecturerid
					}
				})
			},
			fileChange(e) {
				this.file = e.target.files[0]
				if(!this.file) {
					alert("请先选择需要上传的文件!")
					return
				}
				var Title = this.file.name
				var userData = '{"Vod":{}}'
				if(this.uploader) {
					this.uploader.stopUpload()
					this.authProgress = 0
					this.statusText = ""
				}
				this.uploader = this.createUploader()
				console.log(userData)
				this.uploader.addFile(this.file, null, null, null, userData)
				this.uploadDisabled = false
				this.pauseDisabled = true
				this.resumeDisabled = true
			},
			authUpload() {
				// 然后调用 startUpload 方法, 开始上传
				if(this.uploader !== null) {
					this.uploader.startUpload()
					this.uploadDisabled = true
					this.pauseDisabled = false
				}
			},
			// 暂停上传
			pauseUpload() {
				if(this.uploader !== null) {
					this.uploader.stopUpload()
					this.resumeDisabled = false
					this.pauseDisabled = true
				}
			},
			// 恢复上传
			resumeUpload() {
				if(this.uploader !== null) {
					this.uploader.startUpload()
					this.resumeDisabled = true
					this.pauseDisabled = false
				}
			},
			createUploader(type) {
				let self = this
				let uploader = new AliyunUpload.Vod({
					timeout: self.timeout || 60000,
					partSize: self.partSize || 1048576,
					parallel: self.parallel || 5,
					retryCount: self.retryCount || 3,
					retryDuration: self.retryDuration || 2,
					region: self.region,
					userId: self.userId,
					updateVideoTitle:self.liveBroadcastName,
					// 添加文件成功
					addFileSuccess: function(uploadInfo) {
						self.uploadDisabled = false
						self.resumeDisabled = false
						self.statusText = '添加文件成功, 等待上传...'
						console.log("addFileSuccess: " + uploadInfo.file.name,this.updateVideoTitle)
					},
					// 开始上传
					onUploadstarted: function(uploadInfo) {
						if(!uploadInfo.videoId) {
							let createUrl = 'http://www.h3clearning.com/huathree-back/uploadV?Title=' + this.updateVideoTitle;
							axios.get(createUrl).then(({data}) => {
								let uploadAuth = data.data.UploadAuth
								let uploadAddress = data.data.UploadAddress
								let videoId = data.data.VideoId
								uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId)
							})
							self.statusText = '文件开始上传...'
							console.log("onUploadStarted:" + this.updateVideoTitle + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object)
						} else {
							let refreshUrl = 'http://www.h3clearning.com/huathree-back/uploadV?Title=' + uploadInfo.videoId;
							axios.get(refreshUrl).then(({data}) => {
								let uploadAuth = data.data.UploadAuth
								let uploadAddress = data.data.UploadAddress
								let videoId = data.data.VideoId
								uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId)
							})
						}
					},
					// 文件上传成功
					onUploadSucceed: function(uploadInfo) {
						console.log("-------->"+uploadInfo+"onUploadSucceed: " + this.updateVideoTitle + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object)
						console.log('++++++++++++++++++'+uploadInfo.videoId);
						self.statusText = '文件上传成功!';
						self.aliyunVideoId= uploadInfo.videoId;
					},
					// 文件上传失败
					onUploadFailed: function(uploadInfo, code, message) {
						//console.log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message)
						self.statusText = '文件上传失败!'
					},
					// 取消文件上传
					onUploadCanceled: function(uploadInfo, code, message) {
						//console.log("Canceled file: " + uploadInfo.file.name + ", code: " + code + ", message:" + message)
						self.statusText = '文件已暂停上传'
					},
					// 文件上传进度，单位：字节, 可以在这个函数中拿到上传进度并显示在页面上
					onUploadProgress: function(uploadInfo, totalSize, progress) {
						console.log("onUploadProgress:file:" +  this.updateVideoTitle + ", fileSize:" + totalSize + ", percent:" + Math.ceil(progress * 100) + "%")
						let progressPercent = Math.ceil(progress * 100)
						self.authProgress = progressPercent
						self.statusText = '文件上传中...'
					},
					// 上传凭证超时
					onUploadTokenExpired: function(uploadInfo) {
						let refreshUrl = 'http://www.h3clearning.com/huathree-back/refreshVideo?VideoId=' + uploadInfo.videoId;
						axios.get(refreshUrl).then(({data}) => {
							let uploadAuth = data.data.UploadAuth
							uploader.resumeUploadWithAuth(uploadAuth)
							//console.log('upload expired and resume upload with uploadauth ' + uploadAuth)
						})
						self.statusText = '文件超时...'
					},
					// 全部文件上传结束
					onUploadEnd: function(uploadInfo) {
						//console.log("onUploadEnd: uploaded all the files")
						self.statusText = '文件上传完毕'
					}
				}) 
				return uploader;
			}
		},
		components:{
			alert
		},
		mounted(){
			this.getParams();
			if(this.liveBroadcastid==null){
				this.$store.commit('GET_coursewareLiveWrap');
				var s =this.$store.state.coursewareLiveWrap;
				this.liveId = s.liveId;
				this.liveBroadcastid = s.liveBroadcastid;
				this.courseName = s.courseName;
				this.updateTitle = s.updateTitle;
				this.teacherTitle = s.teacherTitle;
				this.lecturerid = s.lecturerid;
				this.pathKey = s.pathKey;
			};
			this.getLiveDetails();
			this.getCommentsList();
			this.getData();
			window.addEventListener("beforeunload",()=>{
				s={
					liveId:this.liveId,
					liveBroadcastid:this.liveBroadcastid,
					courseName:this.courseName,
					updateTitle:this.updateTitle,
					pageTypeNum:this.pageTypeNum,
					courseCompanyid:this.courseCompanyid,
					teacherTitle:this.teacherTitle,
					lecturerid:this.lecturerid,
					pathKey:this.pathKey
				}	
				this.$store.commit('SET_coursewareLiveWrap', s);
			});
		}
	}
</script>

<style>
	.coursewareLiveWrap .liveDynamic p{line-height: 26px;}
	.coursewareLiveWrap .liveDynamic .huifangDiv button{padding: 0;}
	.coursewareLiveWrap .liveDynamic .huifangDiv button:hover{background: transparent;}
</style>